package org.etlt.check;

import org.etlt.extract.Entity;
import org.etlt.extract.Extractor;
import org.etlt.job.JobContext;

public class E2ECheckPoint extends CheckPoint {

    public E2ECheckPoint(CheckPointSetting setting, CheckList checkList) {
        super(setting, checkList);
    }

    public CheckResult check(JobContext context) {
        CheckResult checkResult = new CheckResult(this);
        CheckPointSetting setting = getSetting();
        try (Extractor actualExtractor = context.createExtractor(setting.getActual());
             Extractor expectExtractor = context.createExtractor(setting.getExpected());) {
            for (actualExtractor.extract(context), expectExtractor.extract(context);
                 context.exists(setting.getActual()) && context.exists(setting.getExpected());
                 actualExtractor.extract(context), expectExtractor.extract(context)) {
                Entity actualEntity = context.getEntity(setting.getActual());
                Entity expectEntity = context.getEntity(setting.getExpected());
                // check if data is equal
                if (!actualEntity.equals(expectEntity)
                    && !String.valueOf(actualEntity).equals(String.valueOf(expectEntity))) {
                    checkResult.fail();
                    break;
                } else
                    checkResult.success();
            }

            if (!checkResult.isChecked() &&
                    (!context.exists(setting.getActual()) && !context.exists(setting.getExpected()))) {
                checkResult.success();
            }
            //check if total number is equal
            if (checkResult.isSuccess() &&
                    (context.exists(setting.getActual()) != context.exists(setting.getExpected())))
                checkResult.fail();
        } catch (Exception e) {
//            do nothing
        } finally {
            return checkResult;
        }
    }

    @Override
    public String getDetail(JobContext context) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getCheckList().getName())
                .append(".")
                .append(getName());
        stringBuilder.append(CR);
        stringBuilder.append("description: " + normalize(getSetting().getDescription()));
        stringBuilder.append(CR);
        Extractor expectExtractor = context.getExtractor(getSetting().getExpected());
        stringBuilder.append("expected: " + expectExtractor);
        stringBuilder.append(CR);
        Extractor actualExtractor = context.getExtractor(getSetting().getActual());
        stringBuilder.append("actual: " + actualExtractor);
        return stringBuilder.toString();
    }
}
